const basicAuth=require('basic-auth')
const jwt = require('jsonwebtoken')

/**
 * Auth中间件
 */
class Auth {
	constructor(level) {
		this.level=level || 1
	    Auth.USER=8
		Auth.ADMIN=16
		Auth.SUPER_ADMIN=32
	}
	
	get m(){//中间件处理token
		return async(ctx,next)=>{
			//token 检查
			//token 传递令牌
			const userToken=basicAuth(ctx.req)
			let errMsg='token不合法'
			if(!userToken || !userToken.name){
				throw new global.errs.Forbbiden(errMsg)
			}
			try{
				var decode=jwt.verify(userToken.name,global.config.security.secretKey)
			}catch(e){
				//token不合法
				//token过期
				if(e.name=='TokenExpireError'){
					errMsg='token令牌已过期'
				}
				throw new global.errs.Forbbiden(errMsg)
			}
		
			if(decode.scope < this.level){
				errMsg='权限不足'
				throw new global.errs.Forbbiden(errMsg)
			}
		
			//uid,scope
			ctx.auth={
				uid:decode.uid,
				scope:decode.scope
			}
			
			await next()
		}
	}
	
	static verifyToken(token){
		try{
			console.log('==========')
			console.log(token)
			jwt.verify(token,global.config.security.secretKey)
			return true
		}catch(e){
			return false
		}
	}
}

module.exports={
	Auth
}